<template>
  <div class="confirm-order">
    <div class="header">
      <van-icon name="arrow-left" size="24" @click="goBack" />
      <div class="title">确认订单</div>
    </div>
    <div class="service-guarantee">
      服务保障
      <span>明码标价 | 未上门随时退 | 90天质保</span>
    </div>
    <div class="address-time">
      <div class="address" @click="showAddressEditor = true">
        <van-icon name="location-o" size="24" />
        <span v-if="defaultAddress == '' || defaultAddress == undefined">{{ formattedAddress || '请选择上门地址' }}</span>
        <span v-else>{{ formattedAddress || defaultAddress }}</span>
        <van-icon name="arrow" size="24" />
      </div>
      <div class="time" @click="handleTimePicker">
        <van-icon name="clock-o" size="24" />
        <span>{{ formattedTime || '请选择上门时间' }}</span>
        <van-icon name="arrow" size="24" />
      </div>
    </div>
    <div class="service-item">
      <div class="item-info">
        <div class="item-name">{{ categoryName }}</div>
        <div class="item-count">
          <van-icon name="minus" size="24" @click="decreaseCount" />
          <span>{{ itemCount }}</span>
          <van-icon name="plus" size="24" @click="increaseCount" />
        </div>
      </div>
    </div>
    <div class="item-details">
      <div class="form-section">
        <van-field 
          v-model="itemTypeValue" 
          is-link 
          readonly 
          label="物品类型" 
          placeholder="请选择物品类型" 
          @click="handleTypeClick"
          label-class="required-label"
          :disabled="loadingTypes || itemTypes.length === 0"
          :clickable="!loadingTypes && itemTypes.length > 0"
        />
        <van-popup v-model:show="showPicker" destroy-on-close round position="bottom">
          <van-picker 
            :model-value="pickerValue" 
            :columns="itemTypes" 
            @cancel="showPicker = false"
            @confirm="onItemTypeConfirm" 
            :loading="loadingTypes"
          />
        </van-popup>
      </div>
      <div class="description">
        如有多套或不同类型产品的服务需求，可通过购物车功能进行添加~
      </div>
      <div class="image-upload">
        <span>*物品图片</span>
        <van-uploader
          v-model="uploadedImages"
          :after-read="handleImageUpload"
          :max-count="9"
          preview-size="80px"
          preview-full-image
        >
          <template #tip>
            <span v-if="uploadedImages.length">已上传{{ uploadedImages.length }}张</span>
          </template>
        </van-uploader>
      </div>
      <div class="requirement">
        <h2>需求说明:</h2>
        <p class="hint">如有特殊需求，可通过留言进行补充说明。</p>
        <p class="example">示例：仅周末有时间，请师傅带齐工具，按时上门。</p>
        <van-field v-model="specialRequirements" rows="2" autosize type="textarea" placeholder="如有特殊需求，请在此说明" />
      </div>
      <div class="progress">
        <span>报价进度已完成{{ completionPercentage }}%</span>
        <van-progress :percentage="completionPercentage" color="#ee0a24" />
      </div>
    </div>
    <div class="submit-button">
      <van-button type="primary" block @click="handleSubmit" :disabled="!isFormComplete">立即发布，获得附近师傅报价</van-button>
    </div>

    <!-- 地址编辑弹窗 -->
    <van-popup v-model:show="showAddressEditor" position="bottom" class="address-editor-popup">
      <div class="address-editor-header">
        <span>编辑地址</span>
        <span class="note">个人信息仅用于发布需求，隐私信息完全保密</span>
      </div>
      <div class="address-editor-content">
        <div class="map-address">
          <div class="map-address-info">
            <span class="address-name">{{ useAddress }}</span>
            <van-button type="primary" size="small" @click="useThisAddress">使用该地址</van-button>
          </div>
          <div class="map-address-detail">
            <div class="detail-address">
              <van-icon name="edit" size="24" />
              <span>详细地址</span>
              <van-field v-model="addressDetails.detailedAddress" placeholder="请输入详细地址"
                :rules="[{ required: true, message: '请填写详细地址' }]" />
            </div>
            <div class="region-address">
              <span>所在地区</span>
              <span>江西省南昌市青山湖区艾溪湖管理处</span>
            </div>
          </div>
        </div>
      </div>
      <div class="contact-info">
        <div class="contact-name">
          <van-field v-model="addressDetails.contactName" placeholder="联系人姓名"
            :rules="[{ required: true, message: '请填写联系人姓名' }]" />
          <div class="gender-buttons">
            <van-button type="primary" size="small" :plain="addressDetails.gender !== '先生'"
              @click="addressDetails.gender = '先生'">
              先生
            </van-button>
            <van-button type="primary" size="small" :plain="addressDetails.gender !== '女士'"
              @click="addressDetails.gender = '女士'">
              女士
            </van-button>
          </div>
          <div class="contact-phone">
            <van-field v-model="addressDetails.contactPhone" placeholder="联系人电话" type="tel" :rules="[
              { required: true, message: '请填写联系电话' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
            ]" />
          </div>
        </div>
        <div class="default-address">
          <span>设置默认地址</span>
          <van-switch v-model="addressDetails.isDefaultAddress" />
        </div>
      </div>
      <div class="address-editor-footer">
        <van-button type="danger" size="large" @click="deleteAddress">删除</van-button>
        <van-button type="primary" size="large" @click="saveAddress">保存</van-button>
      </div>
    </van-popup>

    <!-- 空的popup（原时间选择器） -->
    <!-- <van-popup v-model:show="showTimePicker" position="bottom" round>
    </van-popup> -->
     <van-popup v-model:show="timePickerVisible" position="bottom" class="time-picker-popup">
      <div class="time-picker-header">
        <span>您期望上门服务时间</span>
        <span class="note">师傅接单后电话与您确认最终上门时间</span>
      </div>
      <div class="time-picker-content">
        <div class="time-date-list">
          <div
            v-for="(date, index) in timeOptions"
            :key="index"
            :class="{ active: selectedDateIndex === index }"
            @click="selectDate(index)"
          >
            {{ date.label }}
          </div>
        </div>
        <div class="time-slot-list">
          <div
            v-for="(slot, slotIndex) in timeOptions[selectedDateIndex].slots"
            :key="slotIndex"
            :class="{ active: selectedSlotIndex === slotIndex }"
            @click="selectSlot(slotIndex)"
          >
            {{ slot }}
          </div>
        </div>
      </div>
      <div class="time-picker-footer">
        <van-button type="primary" block @click="confirmTime">确定</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script setup name="ConfirmOrder">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { emitter } from '../utils/eventBus'
import { showToast, showConfirmDialog ,showFailToast} from 'vant'
import { getaddressById, getaddAddress, uploadImageApi, getCategoryById, getFindAllTypes,getOrderDetails } from '../api'
import { useUserInfoStore } from '../stores/userInfo'
const formattedTime = ref()
const router = useRouter()
const useAddress = ref("绿地集团写字楼")
const showAddressEditor = ref(false)
const UserInfoStore = useUserInfoStore()
const addressDetails = ref({
  detailedAddress: '',
  contactName: '',
  gender: '先生',
  contactPhone: '',
  isDefaultAddress: false
})
const service=ref()
const categoryName=ref("沙发安装")
const getCategory=async ()=>{
  let category=await getCategoryById(service.value.categoryId)
  categoryName.value=category.categories.categoryName
}
const defaultAddress = ref()
const AddressId1=ref()
const addAddress = ref({
  "userId": 1,
  "addresss": "",
  "status": 1
})
const getdefaultAddress = async () => {
  // console.log('UserInfoStore.$state.uid',UserInfoStore.$state.uid);
  try {
     if(UserInfoStore.$state.uid !=undefined &&UserInfoStore.$state.uid!=''){
      
      addAddress.value.userId = UserInfoStore.$state.uid
      // console.log( '  addAddress.value.userId', addAddress.value.userId);
  }
    
    let result = await getaddressById( addAddress.value.userId )
    if (result && result.address) {
      // console.log(result.address.id);
      defaultAddress.value = result.address.addresss
      AddressId1.value=result.address.id
    }
  } catch (e) {
    console.log("没有默认地址");
  }
}
const formattedAddress = computed(() => {
  const { detailedAddress, contactName, gender, contactPhone } = addressDetails.value
  if (!detailedAddress || !contactName || !contactPhone) return ''
  return `${detailedAddress} (${contactName}${gender} ${contactPhone})`
})

const showTimePicker = ref(false)
const useThisAddress = () => {
  addressDetails.value.detailedAddress = useAddress.value;
  showToast('地址已应用');
}
const saveAddress = async () => {
  if (!addressDetails.value.detailedAddress ||
    !addressDetails.value.contactName ||
    !addressDetails.value.contactPhone) {
    showToast('请完善地址信息');
    return;
  }
  if (addressDetails.value.isDefaultAddress) {
    addAddress.value.status = 0
  }
  addAddress.value.addresss = formattedAddress
  try {
    let retrunId = await getaddAddress(addAddress.value)
    AddressId1.value=retrunId
    showToast('地址保存成功');
    showAddressEditor.value = false;
  } catch (e) {
    console.log("保存失败", e);
  }

};
const deleteAddress = () => {
  showConfirmDialog({
    title: '确认删除',
    message: '确定要删除这个地址吗？',
  }).then(() => {
    addressDetails.value = {
      detailedAddress: '',
      contactName: '',
      gender: '先生',
      contactPhone: '',
      isDefaultAddress: false
    }
    showToast('地址已删除')
    showAddressEditor.value = false
  })
}
const itemCount = ref(1)
const decreaseCount = () => {
  if (itemCount.value > 1) {
    itemCount.value--
  }
}
const increaseCount = () => {
  itemCount.value++
}
const itemTypes = ref([]);
const itemTypeValue = ref('');
const showPicker = ref(false);
const pickerValue = ref([]);
const loadingTypes = ref(true);
const loadTypeError = ref(false);
const selectedTypeId = ref('');
const fetchItemTypes = async () => {
  try {
    loadingTypes.value = true;
    loadTypeError.value = false;
    const response = await getFindAllTypes();
    const typesData = response.data || response;
    
    if (Array.isArray(typesData) && typesData.length > 0) {
      itemTypes.value = typesData.map(type => ({
        text: type.categoryName,
        value: type.categoryId,
        raw: type
      }));
      showToast(`成功加载 ${itemTypes.value.length} 种服务类型`);
    } else {
      loadTypeError.value = true;
      showFailToast('未获取到有效服务类型数据');
    }
  } catch (error) {
    loadTypeError.value = true;
    itemTypes.value = [];
    showFailToast('加载服务类型失败，请重试');
  } finally {
    loadingTypes.value = false;
  }
};
onMounted(() => {
  fetchItemTypes();
});
const handleTypeClick = () => {
  if (loadingTypes.value) {
    showToast('服务类型正在加载，请稍候...');
    return;
  }  
  if (loadTypeError.value) {
    showToast('重新尝试加载服务类型...');
    fetchItemTypes();
    return;
  }  
  if (itemTypes.value.length > 0) {
    if (selectedTypeId.value) {
      const index = itemTypes.value.findIndex(item => item.value === selectedTypeId.value);
      if (index !== -1) {
        pickerValue.value = [itemTypes.value[index].value];
      }
    }
    showPicker.value = true;
  } else {
    showFailToast('暂无可用的服务类型');
  }
};
const onItemTypeConfirm = ({ selectedOptions }) => {
  showPicker.value = false;
  if (selectedOptions && selectedOptions.length > 0) {
    const selected = selectedOptions[0];
    itemTypeValue.value = selected.text;
    selectedTypeId.value = selected.value;
  }
};

const uploadedImages = ref([])
const handleImageUpload = async (file) => {
   try {
    if (Array.isArray(file)) {
      const uploadPromises = file.map(item => uploadImageApi(item.file))
      const results = await Promise.all(uploadPromises)
      
      results.forEach(response => {
        if (response && response.url) {
          uploadedImages.value.push({ 
            url: response.url,
            status: 'done',
            uid: Date.now() + Math.random().toString(36).substr(2, 9)
          })
        }
      })     
      showToast(`成功上传${results.length}张图片`)
      return
    }  
    const response = await uploadImageApi(file.file)    
    if (response && response.url) {
      uploadedImages.value.push({
        url: response.url,
        status: 'done',
        uid: Date.now() + Math.random().toString(36).substr(2, 9)
      })
      showToast('图片上传成功')
    } else {
      file.status = 'failed'
      file.message = '上传失败'
      showToast('图片上传失败')
    }
   } catch (error) {
    showToast('图片上传失败')
    file.status = 'failed'
    file.message = error.message || '上传出错'
   }   
}
const specialRequirements = ref('')
const completionPercentage = computed(() => {
   let percentage=0
  if(defaultAddress.value){
     percentage = 50
  }else{
       percentage = 30
  } 
  if (formattedAddress.value) percentage += 20
  if (itemTypeValue.value) percentage += 10
  if (uploadedImages.value.length) percentage += 10
  if (specialRequirements.value) percentage += 10
  return Math.min(percentage, 100)
})
const isFormComplete = computed(() => {
  return (formattedAddress.value || defaultAddress.value)&&
    itemTypeValue.value &&
    uploadedImages.value.length > 0
})
const orderDetails=ref(
  {
   
    "addressId": null,
    "userId": null,
    "categoryId": null,
    "serviceId": null,
    "specialRequirements": "",
    'serviceTime':"",
    "itemQuantity": null,
    "itemImages": "",
    "contactName": "",
    "contactPhone": ""
}
)
const handleSubmit =async () => {
  if (!isFormComplete.value) {
    showToast('请完善所有必填信息')
    return
  }
  const orderData = {
    address: addressDetails.value,
    itemCount: itemCount.value,
    itemType: itemTypeValue.value,
    images: uploadedImages.value.map(img => img.url),
    requirements: specialRequirements.value,
    createdAt: new Date().toISOString()
  }

  // console.log(orderData);
  orderDetails.value.userId=UserInfoStore.$state.uid
  orderDetails.value.addressId=AddressId1.value
  orderDetails.value.categoryId=service.value.categoryId
  orderDetails.value.serviceId=service.value.serviceId
  orderDetails.value.specialRequirements=orderData.requirements
  orderDetails.value.itemQuantity=orderData.itemCount
  orderDetails.value.itemImages=orderData.images[1]
  orderDetails.value.contactName=orderData.address.contactName
  orderDetails.value.contactPhone=orderData.address.contactPhone
  orderDetails.value.serviceTime=formattedTime.value
  

  try{
    //  console.log(orderDetails.value);
let resultOrder= await getOrderDetails(orderDetails.value)
  showToast('订单提交成功')
  router.push({name:'homepage'})
// console.log('resultOrder',resultOrder);
  }catch(e){
    console.log("e",e);
    showToast('订单提交失败')
  }
}
const getWeekDates = () => {
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const timeSlots = ['08:00-12:00', '13:00-17:00', '18:00-22:00'];
  const weekDates = [];
  
  for (let i = 0; i < 7; i++) {
    const date = new Date();
    date.setDate(date.getDate() + i);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekDay = days[date.getDay()];
    
    weekDates.push({
      label: `${weekDay} ${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
      dateString: `${date.getFullYear()}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
      slots: timeSlots
    });
  }
  
  return weekDates;
};
const timeOptions = ref(getWeekDates());
const selectedDateIndex = ref(0);
const selectedSlotIndex = ref(0);
const timePickerVisible = ref(false);

const handleTimePicker = () => {
  timePickerVisible.value = true;
};

const selectDate = (index) => {
  selectedDateIndex.value = index;
  selectedSlotIndex.value = 0;
};

const selectSlot = (index) => {
  selectedSlotIndex.value = index;
};

const confirmTime = () => {
  const selectedDate = timeOptions.value[selectedDateIndex.value];
  const selectedSlot = selectedDate.slots[selectedSlotIndex.value];
  formattedTime.value = `${selectedDate.label} ${selectedSlot}`;
  timePickerVisible.value = false;
};
// const selectedDateIndex = ref(0);
// const selectedSlotIndex = ref(0);
// const timePickerVisible = ref(false);


// const handleTimePicker = () => {
//   timePickerVisible.value = true;
// };

// const selectDate = (index) => {
//   selectedDateIndex.value = index;
//   selectedSlotIndex.value = 0;
// };

// const selectSlot = (index) => {
//   selectedSlotIndex.value = index;
// };

// const confirmTime = () => {
 
  
//   const selectedDate = timeOptions.value[selectedDateIndex.value];
//   const selectedSlot = selectedDate.slots[selectedSlotIndex.value];
//   formattedTime.value = `${selectedDate.label} ${selectedSlot}`;
//   //  console.log('formattedTime',formattedTime);
//   // console.log('formattedTime',formattedTime.value);
//   timePickerVisible.value = false;
// };
const goBack = () => {
  router.push({ name: 'bedInstallation' })
}
onMounted(() => {
  emitter.on('news-service', (message) => {
    service.value=message.newsService
    
    getCategory()
  })
  getdefaultAddress()  
})
</script>


<style scoped>
.confirm-order {
  padding-bottom: 80px;
}

.header {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

.service-guarantee {
  padding: 10px 15px;
  font-size: 12px;
  color: #666;
  background-color: #f9f9f9;
  display: flex;
  justify-content: space-between;
}

.address-time {
  margin: 15px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.address,
.time {
  padding: 15px;
  display: flex;
  align-items: center;
  background-color: white;
}

.address {
  border-bottom: 1px solid #f5f5f5;
}

.address span,
.time span {
  flex: 1;
  margin: 0 10px;
}

.service-item {
  margin: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-count {
  display: flex;
  align-items: center;
}

.item-count span {
  margin: 0 10px;
}

.item-details {
  margin: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.type,
.image-upload,
.requirement {
  margin-bottom: 15px;
}

.type span:first-child,
.image-upload span {
  color: #ee0a24;
}

.description {
  font-size: 12px;
  color: #999;
  margin: 10px 0;
}

.upload-icon {
  margin-top: 10px;
  width: 80px;
  height: 80px;
  border: 1px dashed #ccc;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
}

.requirement-text {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.example {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}

.progress {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.submit-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background-color: white;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.address-editor-popup {
  height: 80%;
}

.address-editor-header {
  padding: 15px;
  text-align: center;
  position: relative;
}

.address-editor-header .note {
  display: block;
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.address-editor-content {
  padding: 15px;
}

.map-address-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-address,
.region-address {
  margin-bottom: 15px;
}

.contact-name,
.contact-phone {
  display: flex;
  margin-bottom: 15px;
}

.gender-buttons {
  display: flex;
  margin-left: 15px;
}

.gender-buttons .van-button {
  margin-right: 5px;
}

.default-address {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.address-editor-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
}

.address-editor-footer .van-button {
  flex: 1;
  border-radius: 0;
}

.time-picker-popup {
  width: 100%;
}

.requirement-input {
  margin-bottom: 10px;
}






.time-picker-popup {
  background-color: white;
  border-radius: 16px 16px 0 0;
  padding: 16px;
}

.time-picker-header {
  margin-bottom: 16px;
}

.time-picker-header .note {
  color: #666;
  font-size: 14px;
}

.time-date-list {
  display: flex;
  overflow-x: auto;
  margin-bottom: 16px;
}

.time-date-list div {
  padding: 8px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-right: 8px;
  cursor: pointer;
}

.time-date-list div.active {
  background-color: #ee0a24;
  color: white;
  border-color: #ee0a24;
}

.time-slot-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

.time-slot-list div {
  padding: 8px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
}

.time-slot-list div.active {
  background-color: #ee0a24;
  color: white;
  border-color: #ee0a24;
}

.time-picker-footer {
  margin-top: 24px;
}
</style>